package com.d3works.apps.supplychain.web;

import com.d3works.apps.ReportFactory;
import com.d3works.apps.base.callable.ControllerCallableTool;
import com.d3works.apps.report.engine.ReportSettings;
import com.d3works.apps.supplychain.db.Mrp;
import com.d3works.apps.supplychain.db.repo.MrpRepository;
import com.d3works.apps.supplychain.exception.SupplychainExceptionMessage;
import com.d3works.apps.supplychain.report.IReport;
import com.d3works.apps.supplychain.service.MrpFilterSaleOrderLineService;
import com.d3works.apps.supplychain.service.MrpService;
import com.d3works.db.tenants.TenantResolver;
import com.d3works.exception.D3worksException;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.util.List;
import java.util.stream.Collectors;

@Singleton
public class MrpController {

  public void undoManualChanges(ActionRequest request, ActionResponse response) {
    Mrp mrp = request.getContext().asType(Mrp.class);
    MrpService mrpService = Beans.get(MrpService.class);
    MrpRepository mrpRepository = Beans.get(MrpRepository.class);
    try {
      mrpService.undoManualChanges(mrpRepository.find(mrp.getId()));
    } catch (Exception e) {
      TraceBackService.trace(response, e);
      mrpService.reset(mrpRepository.find(mrp.getId()));
    } finally {
      response.setReload(true);
    }
  }

  public void runCalculation(ActionRequest request, ActionResponse response) {

    Mrp mrp = request.getContext().asType(Mrp.class);
    MrpService mrpService = Beans.get(MrpService.class);
    MrpRepository mrpRepository = Beans.get(MrpRepository.class);
    try {
      if (mrpService.isOnGoing(mrpRepository.find(mrp.getId()))) {
        response.setInfo(I18n.get(SupplychainExceptionMessage.MRP_ALREADY_STARTED));
        return;
      }

      final String tenantId = TenantResolver.currentTenantIdentifier();
      final String tenantHost = TenantResolver.currentTenantHost();
      mrpService.setMrp(Beans.get(MrpRepository.class).find(mrp.getId()));
      mrpService.setTenantId(tenantId);
      mrpService.setTenantHost(tenantHost);

      // Tool class that does not need to be injected
      ControllerCallableTool<Mrp> mrpControllerCallableTool = new ControllerCallableTool<>();

      mrpControllerCallableTool.runInSeparateThread(mrpService, response);
    } catch (Exception e) {
      TraceBackService.trace(response, e);
      mrpService.saveErrorInMrp(mrpRepository.find(mrp.getId()), e);
    } finally {
      response.setReload(true);
    }
  }

  public void generateAllProposals(ActionRequest request, ActionResponse response) {

    try {
      Mrp mrp = request.getContext().asType(Mrp.class);
      Boolean isProposalsPerSupplier =
          (Boolean) request.getContext().get("consolidateProposalsPerSupplier");
      Beans.get(MrpService.class)
          .generateProposals(
              Beans.get(MrpRepository.class).find(mrp.getId()),
              isProposalsPerSupplier != null && isProposalsPerSupplier);
      response.setInfo(I18n.get("Proposals have been generated successfully."));
    } catch (D3worksException e) {
      TraceBackService.trace(response, e);
    } finally {
      response.setReload(true);
    }
  }

  /**
   * Prints the weekly breakdown MRP birt report and shows it to the user.
   *
   * @param request
   * @param response
   */
  public void printWeeks(ActionRequest request, ActionResponse response) {
    Mrp mrp = request.getContext().asType(Mrp.class);
    mrp = Beans.get(MrpRepository.class).find(mrp.getId());
    String name = I18n.get("MRP") + "-" + mrp.getId();

    try {
      String fileLink =
          ReportFactory.createReport(IReport.MRP_WEEKS, name)
              .addParam("mrpId", mrp.getId())
              .addParam("Timezone", getTimezone(mrp))
              .addParam("Locale", ReportSettings.getPrintingLocale(null))
              .addParam(
                  "endDate",
                  Beans.get(MrpService.class).findMrpEndDate(mrp).atStartOfDay().toString())
              .addFormat(ReportSettings.FORMAT_PDF)
              .generate()
              .getFileLink();

      response.setView(ActionView.define(name).add("html", fileLink).map());

    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  private String getTimezone(Mrp mrp) {
    if (mrp.getStockLocation() == null || mrp.getStockLocation().getCompany() == null) {
      return null;
    }
    return mrp.getStockLocation().getCompany().getTimezone();
  }

  /**
   * Prints the list MRP birt report and shows it to the user.
   *
   * @param request
   * @param response
   */
  public void printList(ActionRequest request, ActionResponse response) {
    Mrp mrp = request.getContext().asType(Mrp.class);
    String name = I18n.get("MRP") + "-" + mrp.getId();

    try {
      String fileLink =
          ReportFactory.createReport(IReport.MRP_LIST, name)
              .addParam("mrpId", mrp.getId())
              .addParam("Timezone", getTimezone(mrp))
              .addParam("Locale", ReportSettings.getPrintingLocale(null))
              .addFormat(ReportSettings.FORMAT_PDF)
              .generate()
              .getFileLink();

      response.setView(ActionView.define(name).add("html", fileLink).map());

    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void setSaleOrderLineSetDomain(ActionRequest request, ActionResponse response) {
    Mrp mrp = request.getContext().asType(Mrp.class);

    try {
      List<Long> idList =
          Beans.get(MrpFilterSaleOrderLineService.class)
              .getSaleOrderLinesComplyingToMrpLineTypes(mrp);

      String idListStr = idList.stream().map(Object::toString).collect(Collectors.joining(","));

      response.setAttr("saleOrderLineSet", "domain", "self.id IN (" + idListStr + ")");
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}
